package com.process.controller;


import com.auth.common.result.Result;
import com.auth.model.process.ProcessTemplate;
import com.auth.model.process.ProcessType;
import com.auth.utils.BooleanUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.process.service.OaProcessService;
import com.process.service.OaProcessTemplateService;
import com.process.service.OaProcessTypeService;
import exception.BusinessException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 审批模板 前端控制器
 * </p>
 *
 * @author tang
 * @since 2023-07-23
 */
@Api(tags = "流程模版入口")
@RestController
@RequestMapping("/admin/process/processTemplate")
public class OaProcessTemplateController {
    private final OaProcessTemplateService processTemplateService;
    private final OaProcessService processService;
    private final OaProcessTypeService processTypeService;
    public OaProcessTemplateController(OaProcessTemplateService processTemplateService, OaProcessTypeService processTypeService, OaProcessService processService) {
        this.processTemplateService = processTemplateService;
        this.processTypeService = processTypeService;
        this.processService = processService;
    }

    @ApiOperation("获取分页审批模版数据")
    @GetMapping("/{page}/{limit}")
    public Result index(@PathVariable Long page,
                        @PathVariable Long limit) {
        IPage<ProcessTemplate> templateiPage = processTemplateService.selectPageProcessTemplate(new Page<ProcessTemplate>(page, limit));
        if (null != templateiPage) {
            List<ProcessTemplate> records = templateiPage.getRecords();
            for (ProcessTemplate record : records) {
                ProcessType processType = processTypeService.getOne(new LambdaQueryWrapper<ProcessType>().eq(ProcessType::getId, record.getProcessTypeId()));
                if (null != processType) {
                    record.setProcessTypeName(processType.getName());
                }
            }
            return Result.ok(templateiPage);
        } else {
            return Result.fail();
        }
    }

    @ApiOperation(value = "获取")
    @GetMapping("get/{id}")
    public Result get(@PathVariable Long id) {
        ProcessTemplate processTemplate = processTemplateService.getById(id);
        return Result.ok(processTemplate);
    }

    @ApiOperation(value = "新增")
    @PostMapping("save")
    public Result save(@RequestBody ProcessTemplate processTemplate) {
        processTemplateService.save(processTemplate);
        return Result.ok();
    }

    @ApiOperation(value = "修改")
    @PutMapping("update")
    public Result updateById(@RequestBody ProcessTemplate processTemplate) {
        processTemplateService.updateById(processTemplate);
        return Result.ok();
    }

    @ApiOperation(value = "删除")
    @DeleteMapping("remove/{id}")
    public Result remove(@PathVariable Long id) {
        processTemplateService.removeById(id);
        return Result.ok();
    }

    @ApiOperation("上传流程定义")
    @PostMapping("/uploadProcessDefinition")
    public Result uploadProcessDefinition(MultipartFile file) throws IOException {
        // 获取classes目录位置
        String path = new File(ResourceUtils.getURL("classpath:").getPath())
                .getAbsolutePath();
        // 设置上传的文件夹
        File tmp = new File(path + "/activity");
        if (BooleanUtils.not(tmp.exists())) {
            tmp.mkdirs();
        }
        // 创建空文件夹,实现文件写入
        String filename = file.getOriginalFilename();
        File zipFile = new File(path + "/activity/" + filename);
        // 保存文件
        file.transferTo(zipFile);
        return Result.ok(new HashMap<String, Object>(0) {{
            put("processDefinitionPath", "activity/" + filename);
            put("processDefinitionKey", filename.substring(0, filename.lastIndexOf(".")));
        }});
    }

    /**
     * 部署流程定义（即发布流程）
     *
     * @author Tangjiachang
     * @date 2023/7/23 15:59
     * @param id:
     * @return Result
     **/
    @ApiOperation("流程发布接口")
    @GetMapping("/publish/{id}")
    @Transactional(rollbackFor = Exception.class)
    public Result publish(@PathVariable Long id) {
        try {
            // 修改模版发布状态，1表示发布,0表示未发布
            String processDefinitionPath = processTemplateService.publish(id);
            if (StringUtils.isNoneBlank(processDefinitionPath)) {
                processService.deployByZipFile(processDefinitionPath);
            }
            return Result.ok();
        } catch (Exception e) {
            // 回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new BusinessException(5102,"审批模版" + e.getLocalizedMessage());
        }
    }
}

